<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/9/18
 * Time: 14:41
 */

namespace app\api\controller;

use think\Db;
use org\Qiniu;

class Timing extends Base
{
    public function xiaobb()
    {
        //         $db2 = Db::connect('mysql://panson:panson2020app@121.196.57.236:3306/panson#utf8');
//        $res = $db2->table('up_goods')
//            ->where('good_thumb',null)
//            ->field('good_name,good_coding,good_pinming,good_type')
//            ->select();
//        $cellname = [
//            '名字', '款号', '品名', '类型'
//        ];
//        exportExcel('orderinfo',time(),$cellname,$res);
//         $res = $db2->table('up_u_user_son')->alias('sg')
//             ->join('up_school s','sg.uson_school=s.school_id','LEFT')
//             ->field('uson_username,school_name,user_gender,uson_year,uson_grade,uson_class')
//             ->select();
//         $cellname = [
//             '姓名', '学校', '性别', '入学年份', '年级', '班级'
//         ];
//         $status = ['user_gender'];
//         $values = [
//             'user_gender' => [1 => '男',2 => '女']
//         ];
//         exportExcel('order',time(),$cellname,$res,$status,$values);
//        dump($res);
    }

    /**
     * 自营商城的订单相关定时器（1分一跑）
     */
    public function selfshop()
    {
        set_time_limit(0);
        //定时器1：解答超过1小时未提交则清除状态;定时器3：未答题的一小时后关闭
        //1-1：自营订单的超时自动取消
        $today = date('Y-m-d H:i:s');
        $time = time();
        $one_hour_ago = date("Y-m-d H:i:s", ($time - 1800));
        $where['is_pay'] = 0;
        $where['order_contract'] = ['<>', 3];
        $where['o.is_delete'] = 0;
        $where['o.created_at'] = ['<=', $one_hour_ago];
        $field = 'o.order_id,goods_id,num,attr_id,order_contract';
        $res = Db::table('up_self_order')->alias('o')
            ->join('up_self_order_detail od', 'o.order_id=od.order_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->select();
//        dump($res);die;
        if ($res) {
            Db::startTrans();
            try {
                foreach ($res as $k => $v) {
                    if ($v['order_contract'] == 1) {
                        //1、加上商品的库存
                        Db::table('up_self_goods')->where('good_id', $v['goods_id'])->setInc('good_stock', $v['num']);
                        //2、加上attr的库存
                        Db::table('up_self_goods_attr')->where('attr_id', $v['attr_id'])->setInc('stock', $v['num']);
                    }
                    //增补的不用加了
//                    else{
//                        //1、加上商品的库存
//                        Db::table('up_goods')->where('good_id',$v['goods_id'])->setInc('good_stock',$v['num']);
//                        //2、加上attr的库存
//                        Db::table('up_goods')->where('good_id',$v['goods_id'])->setInc("good_{$v['attr_id']}",$v['num']);
//                    }
                }
                //3、改变订单状态
                Db::table('up_self_order o')->where($where)->setField('is_pay', 2);
                Db::commit();
                return 1;
            } catch (\Exception $e) {
                Db::rollback();
                return 2;
            }
        }
    }

    /**
     * 自营商城的订单相关定时器（自动收货和7天售后）
     */
    public function selfshop2()
    {
        set_time_limit(0);
        //定时器1：解答超过1小时未提交则清除状态;定时器3：未答题的一小时后关闭
        //1-1：30天未收货自动收货
        $today = date('Y-m-d H:i:s');
        $time = time();
        $one_hour_ago = date("Y-m-d H:i:s", ($time - 3600 * 24 * 24));
        $where['is_pay'] = 1;
        $where['is_send'] = 1;
        $where['order_contract'] = ['<>', 3];
        $where['is_delete'] = 0;
        $where['send_time'] = ['<=', $one_hour_ago];
        Db::table('up_self_order')
            ->where($where)
            ->update([
                'is_send' => 2,
                'confirm_time' => $today
            ]);
        //1-1：超过7天未售后则不能再申请
        $one_hour_ago = date("Y-m-d H:i:s", ($time - 3600 * 24 * 7));
        unset($where['send_time']);
        $where['is_send'] = ['>=', 2];
        $where['is_sale'] = 0;
        $where['confirm_time'] = ['<=', $one_hour_ago];
        Db::table('up_self_order')->where($where)->setField('is_sale', 1);
        return 1;
    }

    /**
     * 8小时之后再推送给erp
     */
    public function erpZengbuHours()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $hours = Db::table('up_about')->where('id', 9)->value('content');
//        $hours = (int)$hours;
        $hours_ago = date("Y-m-d H:i:s", ($time - 3600 * $hours));
        $where['is_pay'] = 1;
        $where['order_contract'] = 2;
        $where['o.is_delete'] = 0;
        $where['o.is_send'] = 0;
        $where['o.order_push_erp'] = 1;
        $where['o.order_cancel_status'] = ['<=', 2];
        $where['o.pay_time'] = ['<=', $hours_ago];
        $field = 'o.order_no,o.order_id,o.name,o.mobile,o.address,o.order_address2,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',o.order_erp_year,o.order_erp_done,o.order_back_order_id,o.created_at,o.remark,o.pay_type';
        $ids = '15923920265889501,15923965045850273,15923967655731051';
        $ids .= ',15923967957642564,15923968251398936';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'us.uson_school=s.school_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->page(1,50)
            ->select();
       // dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_no'],
//                    'iSaleType' => 2, //1统购  2增补
                    'iBusiness' => 1, //1 是增补，2是换货的增补
                    'dOrderMoney' => $v['all_goods_price'],
                    'dFreight' => $v['express_original_price'],
                    'cReceiveName' => $v['name'],
                    'cReceiveMobile' => $v['mobile'],
                    'cReceiveAddress' => $v['order_address2'],
//                    'cStuName' => $v['uson_username'] ?: '',
//                    'cStuID' => $v['uson_idcard'] ?: '',
//                    'cStuMobile' => $v['uson_parent_phone'] ?: '',
                    'cStuSchool' => $v['school_erp'] ?: '',
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cHPreDate' => $v['order_erp_done'] ? date('Y-m-d',strtotime($v['order_erp_done'])) : '',
                    'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                    'cStuGrade' => $v['uson_grade'] ?: '',
                    'cStuClass' => $v['uson_class'] ?: '',
                    'iYears' => $v['order_erp_year'],
//                    'cPreDate' => $v['order_erp_done'],
                    'cSerialNum' => $v['order_back_order_id'],
                    'Oldordercode' => '',
                    'cRemark' => $v['remark'],
                    'cDate' => substr($v['created_at'], 0, 10)
                ];
                $field = 'goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field($field)
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_no'] . $v['order_id']
                ];
                $url = "http://36.152.23.203:4939/Api/App/SaleOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->update(['order_push_erp' => 2,'new_erp_have' => 2]);
                }else{
                    dump($result);
                }
            }
        }
    }

    /**
     * 8小时之后再推送给erp
     */
    public function erpZengbuHoursForError()
    {
        
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $hours = Db::table('up_about')->where('id', 9)->value('content');
        $hours = (int)$hours;
        $hours_ago = date("Y-m-d H:i:s", ($time - 3600 * $hours));
        $where['is_pay'] = 1;
        $where['order_contract'] = 2;
        $where['o.is_delete'] = 0;
        $where['o.is_send'] = 0;
        $where['o.order_push_erp'] = 1;
        $where['o.order_cancel_status'] = ['<=', 2];
        $where['o.order_no'] = '202111101228214376674';
        $field = 'o.order_no,o.order_id,o.name,o.mobile,o.address,o.order_address2,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',o.order_erp_year,o.order_erp_done,o.order_back_order_id,o.created_at,o.remark,o.pay_type';
        $ids = '15923920265889501,15923965045850273,15923967655731051';
        $ids .= ',15923967957642564,15923968251398936';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'us.uson_school=s.school_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->page(1,50)
            ->select();
       dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_no'],
//                    'iSaleType' => 2, //1统购  2增补
                    'iBusiness' => 1, //1 是增补，2是换货的增补
                    'dOrderMoney' => $v['all_goods_price'],
                    'dFreight' => $v['express_original_price'],
                    'cReceiveName' => $v['name'],
                    'cReceiveMobile' => $v['mobile'],
                    'cReceiveAddress' => $v['order_address2'],
//                    'cStuName' => $v['uson_username'] ?: '',
//                    'cStuID' => $v['uson_idcard'] ?: '',
//                    'cStuMobile' => $v['uson_parent_phone'] ?: '',
                    'cStuSchool' => $v['school_erp'] ?: '',
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cHPreDate' => $v['order_erp_done'] ? date('Y-m-d',strtotime($v['order_erp_done'])) : '',
                    'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                    'cStuGrade' => $v['uson_grade'] ?: '',
                    'cStuClass' => $v['uson_class'] ?: '',
                    'iYears' => $v['order_erp_year'],
//                    'cPreDate' => $v['order_erp_done'],
                    'cSerialNum' => $v['order_back_order_id'],
                    'Oldordercode' => '',
                    'cRemark' => $v['remark'],
                    'cDate' => substr($v['created_at'], 0, 10)
                ];
                $field = 'goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field($field)
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_no'] . $v['order_id']
                ];
                $url = "http://36.152.23.203:4939/Api/App/SaleOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->update(['order_push_erp' => 2,'new_erp_have' => 2]);
                }else{
                    dump($result);
                }
            }
        }
    }

    /**
     * 同步物流信息
     */
    public function getWuliu()
    {
        extract(input());
        //模拟erp返回物流信息时改订单状态
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $return = [
            'errcode' => 0,
            'errmsg' => '',
            'id' => '',
            'code' => '',
            'tradeid' => '',
            'data' => '',
        ];
        $datas = json_decode(json_encode($logisticsList), true);
        if ($datas) {
            Db::startTrans();
            try {
                foreach ($datas as $k => $v) {
                    $SOURTYPE = $v['SOURTYPE'];
                    $APP_DOCNO = $v['APP_DOCNO'];
                    $COMNAME = $v['COMNAME'];
                    $FASTNO = $v['FASTNO'];
                    if ($SOURTYPE == 1) { //1 是增补，2是换货的增补
                        $order = Db::table('up_self_order')->where('order_no', $APP_DOCNO)->field('order_id,is_send')->find();
                        $is_send = $order['is_send'];
                        if ($is_send == 0) {
                            $res = Db::table('up_self_order')
                                ->where('order_no', $APP_DOCNO)
                                ->update([
                                    'is_send' => 1,
                                    'send_time' => $today,
                                    'updated_at' => $today,
                                    'express' => $COMNAME,
                                    'express_no' => $FASTNO,
                                ]);
                            $res = Db::table('up_self_order_detail')
                                ->where('order_id', $order['order_id'])
                                ->update([
                                    'updated_at' => $today,
                                    'detail_express' => $COMNAME,
                                    'detail_express_no' => $FASTNO,
                                ]);

                        }
                    } else {
                        $order_id = Db::table('up_self_order_tui')
                            ->where('order_erp_wl_no', $APP_DOCNO)
                            ->value('order_id');
                        if ($order_id) {
                            $res = Db::table('up_self_order_tui')
                                ->where('order_erp_wl_no', $APP_DOCNO)
                                ->where('status', 2)
                                ->update([
                                    'is_send' => 1,
                                    'send_time' => $today,
                                    'updated_at' => $today,
                                    'merchant_express' => $COMNAME,
                                    'merchant_express_no' => $FASTNO,
                                ]);
                            $jj_deids = Db::table('up_self_order_tui')
                                ->where('order_erp_wl_no', $APP_DOCNO)
                                ->where('status', 2)
                                ->column('order_detail_id');
                            Db::table('up_self_order_detail')
                                ->where('detail_id', 'in', $jj_deids)
                                ->setField('refund_status', 2);

                            $sale_status = Db::table('up_self_order')
                                ->where('order_id', $order_id)
                                ->value('sale_status');
                            if ($sale_status != 0) {
                                Db::table('up_self_order')
                                    ->where('order_id', $order_id)
                                    ->setField('tui_status', 1);
                            }
                        }
                    }
                }
                Db::commit();
                return json($return);
            } catch (\Exception $e) {
                Db::rollback();
                $return['errcode'] = -1;
                $return['errmsg'] = '';
                return json($return);
            }

        }else{
            exit();
        }
    }

    /**
     * 未发货之前取消订单的，发给erp
     */
    public function cancelOrderErp()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $where = [];
        $where['is_pay'] = 2;
        $where['order_contract'] = 2;
        $where['o.is_delete'] = 0;
        $where['o.order_push_erp'] = 2; //没推过的不用
        $where['o.order_cancel_push_erp'] = 1;
        $where['o.order_cancel_status'] = 3;
        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',order_cancel_number,order_cancel_time,order_cancel_remark,new_erp_have';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'us.uson_school=s.school_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->select();
//        dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                $master = [
                    'cAppOrderNo' => $v['order_cancel_number'],
                    'cOrgOrderNo' => $v['order_no'],
                    'cDate' => substr($v['order_cancel_time'], 0, 10),
                    'iType' => 2, //2是增补还未发货就取消了订单  4是收货完成以后退货
                    'dTotRetamt' => $v['all_goods_price'] + $v['express_original_price'],
                    'cStuName' => $v['uson_username'],
                    'cStuID' => $v['uson_idcard'],
                    'cStuMobile' => $v['uson_parent_phone'],
                    'cStuSchool' => $v['school_erp'],
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cStuGrade' => $v['uson_grade'],
                    'cStuClass' => $v['uson_class'],
                    'cRemark' => $v['order_cancel_remark'],
                    'isInit' => $v['new_erp_have'] % 2,
                ];
                $details = Db::table('up_self_order_detail')->alias('od')
                    ->join('up_self_order o', 'od.order_id=o.order_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where('od.order_id', $v['order_id'])
                    ->field('goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,num dQty,CAST(s.user_gender AS CHAR) iSex')
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_cancel_number'] . $v['order_id']
                ];
                $url = "http://36.152.23.203:4939/Api/App/RefundOrderSync";
                $result = $this->curl_erp($url, json_encode($body));
//                    dump($result);die;
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    Db::table('up_self_order')
                        ->where('order_id', $v['order_id'])
                        ->setField('order_cancel_push_erp', 2);
                }else{
                    dump($result);
                }
            }
        }
        //2、售后的推不管退还是换，先推个售后
        $where2 = [];
        $where2['tui_type'] = 2;
        $where2['status'] = 2;
        $where2['erp_push'] = 1;

        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,o.name,o.mobile,o.address,o.order_address2,o.order_back_order_id';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',t.type,t.order_erp_wl_no,o.pay_type';
        $field .= ',t.erp_year,t.erp_done,t.express,t.express_no,t.remark,t.created_at,t.status_time,new_erp_have';

        $datas = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order o', 't.order_id=o.order_id', 'LEFT')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'us.uson_school=s.school_id', 'LEFT')
            ->where($where2)
//            ->where('order_erp_wl_no','in','app1592399658627701,app1592400067811015')
            ->field($field)
            ->group('order_erp_wl_no')
            ->select();
//        dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                //A:先推退货
                $youhua_status = false;
                $master = [
                    'cAppOrderNo' => $v['order_erp_wl_no'] . 'T', //防止跟下面的新单重复单号
                    'cOrgOrderNo' => $v['order_no'],
                    'iType' => $v['type'] + 2, //2是增补还未发货就取消了订单  3是收货完成以后换货  4是收货完成以后退货
                    'dTotRetamt' => $v['all_goods_price'],
                    'cStuName' => $v['uson_username'],
                    'cStuID' => $v['uson_idcard'],
                    'cStuMobile' => $v['uson_parent_phone'],
                    'cStuSchool' => $v['school_erp'],
                    'cSchoolName' => $v['school_name'] ?: '',
                    'cStuGrade' => $v['uson_grade'],
                    'cStuClass' => $v['uson_class'],
                    'cComName' => $v['express'],
                    'cFastNo' => $v['express_no'],
                    'cRemark' => $v['remark'],
                    'cDate' => $v['status_time'],
                    'isInit' => $v['new_erp_have'] % 2,
                ];
                $details = Db::table('up_self_order_tui')->alias('t')
                    ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                    ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                    ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                    ->where($where2)
                    ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                    ->field('od.goods_coding_unique cUniqueNumber,good_coding cProCode,attr_id cProSize,num dQty,CAST(s.user_gender AS CHAR) iSex')
                    ->select();
                $body = [
                    'Head' => $master,
                    'Rows' => $details,
                    'Tradeid' => $v['order_erp_wl_no'] . $v['order_id'] . 'T'
                ];
               // dump($body);die;
                $url = "http://36.152.23.203:4939/Api/App/RefundOrderSync";
                $result = $this->curl_erp($url, json_encode($body));//dump($result);die;
                if (isset($result['errcode']) && $result['errcode'] == 0) {
                    $youhua_status = true;
                }else{
                    dump($result);
                }
                //B:换货的再推增补单
                if ($v['type'] == 1 && $youhua_status == true) {
                    $master = [
                        'cAppOrderNo' => $v['order_erp_wl_no'],
                        'iBusiness' => 2, //1 是增补，2是换货的增补
                        'dOrderMoney' => $v['all_goods_price'],
                        'dFreight' => $v['express_original_price'],
                        'cReceiveName' => $v['name'],
                        'cReceiveMobile' => $v['mobile'],
                        'cReceiveAddress' => $v['order_address2'],
//                            'STU_NAME' => $v['uson_username'],
//                            'STU_ID' => $v['uson_idcard'],
//                            'STU_PHONE' => $v['uson_parent_phone'],
                        'cStuSchool' => $v['school_erp'],
                        'cSchoolName' => $v['school_name'] ?: '',
                        'cHPreDate' => $v['erp_done'] ? date('Y-m-d',strtotime($v['erp_done'])) : '',
                        'cPayMethod' => $v['pay_type'] == 1 ? '微信' : '支付宝',
                        'cStuGrade' => $v['uson_grade'],
                        'cStuClass' => $v['uson_class'],
                        'iYears' => $v['erp_year'],
//                            'PREDATE' => $v['erp_done'],
                        'cSerialNum' => $v['order_back_order_id'],
                        'cOldOrderCode' => $v['order_no'],
                        'cDate' => $today,
                        'cRemark' => '',
                    ];
                    $field = 'erp_huan_uninumber cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                    $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                    $details = Db::table('up_self_order_tui')->alias('t')
                        ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                        ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                        ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                        ->where($where2)
                        ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                        ->field($field)
                        ->select();
                    $body = [
                        'Head' => $master,
                        'Rows' => $details,
                        'Tradeid' => $v['order_erp_wl_no'] . $v['order_id']
                    ];
					// dump($body);die;
                    $url = "http://36.152.23.203:4939/Api/App/SaleOrderSync";
                    $result = $this->curl_erp($url, json_encode($body));
                    if (isset($result['errcode']) && $result['errcode'] == 0) {
                        Db::table('up_self_order_tui')
                            ->where($where2)
                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                            ->setField('erp_push', 2);
                    }else{
                        dump($result);
                    }
                } else {
                    if ($youhua_status == true) {
                        Db::table('up_self_order_tui')
                            ->where($where2)
                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                            ->setField('erp_push', 2);
                    }
                }
            }
        }
    }


    public function dowload()
    {//echo 1;die;
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
            echo "<script> location.href='https://itunes.apple.com/cn/app/id1516439349'; </script>";
        } else {
            echo "<script> location.href='https://a.app.qq.com/o/simple.jsp?pkgname=com.paixun.fz'; </script>";
        }

    }

    /**
     * 获取引导页
     * @return \think\response\Json
     */
    public function getYinDao()
    {
        $lunbo = Db::table('up_appstart')
            ->where('banner_status', 1)
            ->field('banner_img as url')
            ->order('banner_sort ASC')
            ->page(1, 5)
            ->select();
        return json(['status' => 200, 'msg' => $lunbo]);
    }

    /**
     * 同步老用户
     */
    public function oldGoNew()
    {
//        set_time_limit(0);
//        $db2 = Db::connect('mysql://root:5b5u8419,.@221.231.139.177:3306/new#utf8');
//        $subQuery  = $db2->table("app_register_info")
//            ->where('update_time','>=','2018-06-20 23:59:59')
//            ->order('update_time desc')
//            ->buildSql();
//        $data = $db2->table($subQuery."a")
//            ->field("a.loginTel u_phone")
//            ->group('loginTel')
//            ->order('update_time desc')
//            ->select();
//        Db::table('up_z_old_user_note')->insertAll($data);
    }

    //----------------------total_price下面是erp回传问题-------------------------------------------------------------

    public function aaa5()
    {
        set_time_limit(0);
        $db2 = Db::connect('mysql://root:5b5u8419,.@221.231.139.177:3306/new#utf8');
        $status = '已付款,已发货,已排单,已签收';
        $zfstatus = '已付款,已发货,已排单,已签收';
        $exs = '圆通快递,安能快递,申通,申通快递,顺丰,顺丰快递';
//        $subQuery  = $db2->table("app_register_info")
//            ->where('update_time','>=','2018-06-20 23:59:59')
//            ->order('update_time desc')
//            ->buildSql();
//        $data = $db2->table($subQuery."a")
//            ->field("a.loginTel u_phone,concat('用户',a.loginTel) u_name,a.loginPWD u_pass,a.update_time u_time")
//            ->group('loginTel')
//            ->order('update_time desc')
//            ->count();
//        dump($data);die;
//        $page = Db::table('up_z_z')->where('id',1)->value('pages');
//        $field = 'Id order_no,allPrice total_price,expressPrice express_original_price,relName name';
//        $field .= ',relTel mobile,sendAddr address,upZF_time pay_time,zf_last_time send_time';
//        $field .= ',expressName express,expressNum express_no,upTime confirm_time,upZF_time created_at,upZF_time updated_at';
//        $field .= ',car_num all_good_nums,clothPrice all_goods_price,loginTel old_phone';
//        $order = $db2->table('pro_book_info_copy1')
//            ->where('status','in',$status)
//			->where('zf_status','in',$zfstatus)
//			->where('expressName','in',$exs)
////			->where('loginTel','13851664186')
//            ->field($field)
//            ->order('Id ASC')
////            ->page($page,200)
//            ->count();
//        dump($order);die;
//        if(!$order){
//            exit();
//            die;
//        }
//        $field = 'getNum,clothPrice,size,Name,sname,clothCode';
//        foreach ($order as $k => $v){
//            $up = $db2->table('report_order_detail_all_copy')
//                ->where('Id',$v['order_no'])
//                ->field('Name,schoolId,gradeYear')
//                ->find();
////            dump($up);
//            $v['first_good_name'] = $up['Name'];
//            $v['order_school'] = $up['schoolId'];
//            $v['order_erp_year'] = $up['gradeYear'];
//            $order_id = Db::table('up_z_old_order')->insertGetId($v);
//            //----------------------------------------------
//            $detail = $db2->table('report_order_detail_all_copy')
//                ->where('Id',$v['order_no'])
//                ->field($field)
//                ->select();
////            dump($detail);die;
//            foreach ($detail as $k2 => $v2){
//                $de = [ //getNum,clothPrice,size,Name,sname,clothCode,,
//                    'order_id' => $order_id,
//                    'num' => $v2['getNum'],
//                    'unit_price' => $v2['clothPrice'],
//                    'attr_id' => $v2['size'],
//                    'goods_info' => $v2['Name'] . '/' . $v2['size'],
//                    'created_at' => $v['created_at'],
//                    'updated_at' => $v['created_at'],
//                    'detail_express' => $v['express'],
//                    'detail_express_no' => $v['express_no'],
//                    'old_phone' => $v['old_phone'],
//                    'old_stu_name' => $v2['sname'],
//                    'cloth_code' => $v2['clothCode']
//                ];
//                $newgoodcode = Db::table('up_z_new_old_img')->where('old',$v2['clothCode'])->value('new');
//                $goods_id = Db::table('up_goods')->where('good_coding',$newgoodcode)->value('good_id');
//                if(empty($goods_id)){
//                    $goods_id = 0;
//                }
//                $de['goods_id'] = $goods_id;
//                Db::table('up_z_old_order_detail')->insert($de);
//            }
//            Db::table('up_z_z')->where('id',1)->setInc('pages');
//        }
        die;
    }

    /**
     * 售后同意退款之后且打完款之后告诉erp打了多少款
     */
    public function refundMoneyNoticeErp()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        $where = [];
        $where['order_master_status'] = 4;
        $where['order_master_push'] = 1;
        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,order_contract';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',order_cancel_number,order_cancel_time,order_cancel_remark';
        $datas = Db::table('up_self_order')->alias('o')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'us.uson_school=s.school_id', 'LEFT')
            ->where($where)
            ->field($field)
            ->select();
//        dump($datas);die;
    }
    // public function zhangG()
    // {
    // $arr = ['AHB004A00','AHB013A00','AHA018A00','AHC009A00','AHC007B00','HBH002A02','JSD004A00','JSD001A00','JSD002A00','JSD003A00','JSL063A00','JSL068A00','JSL060A00','JSL059A00','JSL069A00','JSL061A00','JSL070A00','JSL065A00','JSL066A00','JSL067A00','AHM007A02','AHM007A03','AHK002A00','JSF001A02','JSF001A03','ZJA002A02','ZJA009A00','ZJA003A00','AHA001A00','AHA003A00','AHA004A00','AHA010A02','AHA011A00','HBB001A00','JSH011A00','JSH003A00','AHF002A00','AHD004A02','JSL008A00','JSL062A00','JSA142A00','JSH001A00','JSA137A00','JSM001A00','JSM001A05','JSB001A00','JSH002A00','JSJ006A00','JSM003A00','JSB007A04','JSB007A00','JSB008A00','JSA069A00','JSJ004A00','JSA098A00','JSL001A00','JSL071A00','JSE006A00','SDP001A02','SCR001A02','JSA065A02','JSA065A03','JSA065A04','JSA043A00','JSA046A00','JSA092A00','JSA095A02','JSA178A00','JSA106A02','JSA152A00','JSA053A10','JSA053A11','JSA053A12','JSA053A13','JSA120A00','JSA001A00','JSA004A00','JSA014A00','JSA003A02','JSA003A03','JSA068A00','JSA002A00','JSA006A00','JSA007A00','JSA008A00','JSA009A00','JSN001A02','JSE002A02','JSE002A03','JSE002A04','JSJ011A02','JSJ011A03','JSA154A02','JSA066A00','JSA088A00','JSA119A00','JSA048A00','JSA025A00','JSA026A00','JSA028A00','JSA029A02','JSA030A00','JSA027A00','JSA121A02','JSA121A00','JSA130A00','JSA044A02','JSA044A03','JSA093A00','JSA061A00','JSA122A00','JSA063B00','JSA063C00','JSA062A00','JSA033A00','JSA031A00','JSA109A00','JSA127A00','JSA089A00','JSA052A00','JSA034A03','JSA034B02','JSA039A00','JSA117A00','JSA032A00','JSA131A00','JSA150A00','JSA135A00','JSA140A00','JSA021A00','JSA024A00','JSA023A02','JSA022A00','JSA055A00','JSA103A00','JSA058A02','JSA037A00','JSA145A00','JSA080A00','JSA064A00','JSA156A00','JSA139A00','JSA087A00','JSA134A02','JSA097A00','JSA132A00','JSA126A00','JSA112A00','JSA111A00','JSA083A00','JSA054A00','JSA054B00','JSA056A02','JSA056A03','JSA057A00','JSA078A00','JSA128A02','JSA107A00','JSA019A00','JSA019A03','JSA019A99','JSA018A00','JSA016A02','JSA016A03','JSA016A04','JSA050A00','JSA038A02','JSA040A00','JSA124A00','JSM012A00','JSA110A00','SJJ001A02','SJJ001A03','ZJD002A00','ZJJ001A02','ZJJ001A03','JSM007A00','JSM002A00','JSM006A00','JSM004A00','HBB003A00','HBB002A00','JSB011A00','JSB006A00','JSB006A04','JSB004A00','JSB012B00','JSB012C00','JSB003A00','JSB003A05','JSB002A00','JSB005A00','AHB001A03','JSJ005A02','ZJA010A00','ZJA001A00','JSN002A00','JSC001A00','JSC007A00','JSN006A00','JSC002A00','JSC005A00','JSC006A00','JSJ003A02','JSJ003A03','JSK001A00','ZJA008A00','JSL004A02','JSL004A03','JSL007A00','JSL022A02','JSL013A02','JSL021A00','JSL040A02','JSL003A00','JSL017A00','JSL005A00','JSL010A02','JSL030A00','JSL002A00','JSL020A00','JSA108A02','SJJ002A02'];

    // $goods_id = Db::table('up_school_good')->where('sg_school_erp','in',$arr)->where('sg_year',2017)->setField('sg_status',2);
    // echo $goods_id;
    // }
    /**
     * 未发货之前取消订单的，发给erp
     */
    public function cancelOrderErpPushNoSend()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $time = time();
        //2、售后的推不管退还是换，先推个售后
        $where2 = [];
        $where2['tui_type'] = 2;
        $where2['type'] = 1;
        $where2['status'] = 2;
        $where2['erp_push'] = 2;
        $where2['t.is_send'] = 0;
        $where2['t.tui_erp_push_no_get'] = 1;

        $field = 'o.order_no,o.order_id,all_goods_price,express_original_price,o.name,o.mobile,o.address,o.order_address2,o.order_back_order_id';
        $field .= ',uson_username,uson_idcard,uson_parent_phone,school_name,school_erp,uson_grade,uson_class';
        $field .= ',t.type,t.order_erp_wl_no';
        $field .= ',t.erp_year,t.erp_done,t.express,t.express_no,t.remark,t.created_at,new_erp_have';

        $datas = Db::table('up_self_order_tui')->alias('t')
            ->join('up_self_order o', 't.order_id=o.order_id', 'LEFT')
            ->join('up_u_user_son us', 'o.order_user_son_id=us.uson_id', 'LEFT')
            ->join('up_school s', 'us.uson_school=s.school_id', 'LEFT')
            ->where($where2)
            ->where('order_erp_wl_no','in','app16215087568242709,app162148554286241702,app162083159484313496,app162124917182312877,app1621260643124318,app162124900144279379')
            ->field($field)
            ->group('order_erp_wl_no')
            ->select();
        //dump($datas);die;
        if ($datas) {
            foreach ($datas as $k => $v) {
                //A:先推退货
                $youhua_status = false;

                //B:换货的再推增补单
                if ($v['type'] == 1) {
                    $master = [
                        'cAppOrderNo' => $v['order_erp_wl_no'],
                        'iBusiness' => 2, //1 是增补，2是换货的增补
                        'dOrderMoney' => $v['all_goods_price'],
                        'dFreight' => $v['express_original_price'],
                        'cReceiveName' => $v['name'],
                        'cReceiveMobile' => $v['mobile'],
                        'cReceiveAddress' => $v['order_address2'],
//                            'STU_NAME' => $v['uson_username'],
//                            'STU_ID' => $v['uson_idcard'],
//                            'STU_PHONE' => $v['uson_parent_phone'],
                        'cStuSchool' => $v['school_erp'],
                        'cStuGrade' => $v['uson_grade'],
                        'cStuClass' => $v['uson_class'],
                        'iYears' => $v['erp_year'],
//                            'PREDATE' => $v['erp_done'],
                        'cSerialNum' => $v['order_back_order_id'],
                        'cOldOrderCode' => $v['order_no'],
                        'cDate' => $today,
                        'cRemark' => '',
                    ];
                    $field = 'erp_huan_uninumber cUniqueNumber,good_coding cProCode,attr_id cProSize,unit_price dPrice,num dQty,s.user_gender iSex';
                    $field .= ',uson_username cStuName,uson_idcard cStuID,uson_parent_phone cStuMobile';
                    $details = Db::table('up_self_order_tui')->alias('t')
                        ->join('up_self_order_detail od', 't.order_detail_id=od.detail_id', 'LEFT')
                        ->join('up_goods g', 'od.goods_id=g.good_id', 'LEFT')
                        ->join('up_u_user_son s', 'od.detail_user_son_id=s.uson_id', 'LEFT')
                        ->where($where2)
                        ->where('t.order_erp_wl_no', $v['order_erp_wl_no'])
                        ->field($field)
                        ->select();
                    $body = [
                        'Head' => $master,
                        'Rows' => $details,
                        'Tradeid' => $v['order_erp_wl_no'] . $v['order_id']
                    ];
                    $url = "http://36.152.23.203:4939/Api/App/SaleOrderSync";
                    $result = $this->curl_erp($url, json_encode($body));
                    if (isset($result['errcode']) && $result['errcode'] == 0) {
                        Db::table('up_self_order_tui')
                            ->where($where2)
                            ->where('order_erp_wl_no', $v['order_erp_wl_no'])
                            ->setField('tui_erp_push_no_get', 2);
                    }else{
                        dump($result);
                    }
                }
            }
        }
    }
	public function mwwtest()
	{
		// exit();
		// $update = [
                        // 'is_pay' => 1,
                        // 'order_no' => '202109021254334655009',
                        // 'order_back_order_id' => '4200001144202109025276434895',
                        // 'order_query_id' => '',
                        // 'pay_time' => '2021-09-02 12:55:42',
                    // ];
                    // $res = Db::table('up_self_order')->where('order_id','280925')->update($update);
					// dump($res);
					// die;
		// $today = date('Y-m-d H:i:s');;
        // $APP_DOCNO = '202105120817175255631';
        // $COMNAME = '顺丰';
        // $FASTNO = 'SF1329850755997';
        // $order = Db::table('up_self_order')->where('order_no', $APP_DOCNO)->field('order_id,is_send')->find();
        // $res1 = Db::table('up_self_order')
            // ->where('order_no', $APP_DOCNO)
            // ->update([
                // 'is_send' => 1,
                // 'send_time' => $today,
                // 'updated_at' => $today,
                // 'express' => $COMNAME,
                // 'express_no' => $FASTNO,
            // ]);
        // $res2 = Db::table('up_self_order_detail')
            // ->where('order_id', $order['order_id'])
            // ->update([
                // 'updated_at' => $today,
                // 'detail_express' => $COMNAME,
                // 'detail_express_no' => $FASTNO,
            // ]);
        // $APP_DOCNO = '202105051912556228984';
        // $COMNAME = '顺丰';
        // $FASTNO = 'SF1333632001323';
        // $order = Db::table('up_self_order')->where('order_no', $APP_DOCNO)->field('order_id,is_send')->find();
        // $res3 = Db::table('up_self_order')
            // ->where('order_no', $APP_DOCNO)
            // ->update([
                // 'is_send' => 1,
                // 'send_time' => $today,
                // 'updated_at' => $today,
                // 'express' => $COMNAME,
                // 'express_no' => $FASTNO,
            // ]);
        // $res4 = Db::table('up_self_order_detail')
            // ->where('order_id', $order['order_id'])
            // ->update([
                // 'updated_at' => $today,
                // 'detail_express' => $COMNAME,
                // 'detail_express_no' => $FASTNO,
            // ]);
			// dump($res1);
			// dump($res2);
			// dump($res3);
			// dump($res4);
	}
}